<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表单名称" prop="formName">
        <el-input
          v-model="queryParams.formName"
          placeholder="请输入表单名称"
          clearable
          size="default"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表单主键" align="center" prop="formId" />
      <el-table-column label="表单名称" align="center" prop="formName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表单名称" prop="formName">
          <el-input v-model="form.formName" placeholder="请输入表单名称" />
        </el-form-item>
        <el-form-item label="表单内容">
          <editor v-model="form.formContent" :min-height="192"></editor>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="formTitle" v-model="formRenderOpen" width="60%" append-to-body>
      <v-form-render :form-data="formData" ref="vFormRef"></v-form-render>
    </el-dialog>

    <el-dialog custom-class="dialogClass" v-model="dialogVisible" :close-on-press-escape="false" fullscreen :before-close="handleClose" append-to-body>
      <v-form-designer ref="vfDesigner" :designer-config="designerConfig">
        <template #customSaveButton>
          <el-button type="text" @click="saveFormJson">
            <i class="el-icon-s-promotion"></i> 保存
          </el-button>
        </template>
      </v-form-designer>
    </el-dialog>

    <el-dialog :title="formTitle" v-model="formOpen" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表单名称" prop="formName">
          <el-input v-model="form.formName" placeholder="请输入表单名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { listForm, delForm, addForm, updateForm } from '@/api/flowable/form';

const queryFormRef = ref(null);
const formRef = ref(null);
const vFormRef = ref(null);
const vfDesigner = ref(null);

const loading = ref(true);
const dialogVisible = ref(false);
const designerConfig = reactive({
  exportCodeButton: false,
});
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const formList = ref([]);
const title = ref('');
const formRenderOpen = ref(false);
const formTitle = ref('');
const formOpen = ref(false);
const open = ref(false);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  formName: null,
  formContent: null,
});
const form = reactive({
  formId: null,
  formName: null,
  formContent: null,
  remark: null,
});
const rules = reactive({});
const formData = reactive({});

const router = useRouter();
const route = useRoute();

onMounted(() => {
  getList();
});

watch(
  () => route.query.t,
  () => {
    if (route.query.t) {
      getList();
    }
  }
);

const getList = () => {
  loading.value = true;
  listForm(queryParams)
    .then((response) => {
      formList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

const cancel = () => {
  formOpen.value = false;
  reset();
};

const reset = () => {
  Object.assign(form, {
    formId: null,
    formName: null,
    formContent: null,
    remark: null,
  });
  formRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.formId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleDetail = (row) => {
  formRenderOpen.value = true;
  formTitle.value = '表单详情';
        nextTick(() => {
        // 回显数据
        vFormRef.value.setFormJson(JSON.parse(row.formContent))
        nextTick(() => {
          // 表单禁用
          vFormRef.value.disableForm();
        })
      })
};

const handleAdd = () => {
  router.push({ path: '/flowable/task/flowForm/index' });
};

const saveFormJson = () => {
  const formJson = vfDesigner.value.getFormJson();
  form.formContent = JSON.stringify(formJson);
  formOpen.value = true;
};

const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？关闭未保存的修改都会丢失？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      done();
    })
    .catch(() => {});
};

const handleUpdate = (row) => {
  router.push({ path: '/flowable/task/flowForm/index', query: { formId: row.formId } });
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.formId) {
        updateForm(form)
          .then(() => {
            ElMessage.success('修改成功');
            formOpen.value = false;
            getList();
          })
          .catch(() => {});
      } else {
        addForm(form)
          .then(() => {
            ElMessage.success('新增成功');
            formOpen.value = false;
            getList();
          })
          .catch(() => {});
      }
      dialogVisible.value = false;
    }
  });
};

const handleDelete = (row) => {
  const formIds = row.formId || ids.value;
  ElMessageBox.confirm('是否确认删除表单编号为"' + formIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return delForm(formIds);
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    })
    .catch(() => {});
};
</script>

<style scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.dialogClass .el-dialog__header {
  padding: 0;
}

.dialogClass .el-dialog__body {
  padding: 0;
}
</style>